package com.yyysj.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yyysj.common.core.constants.HttpConstants;
import com.yyysj.common.core.domain.LoginUser;
import com.yyysj.common.core.domain.Result;
import com.yyysj.common.core.enums.ResultCode;
import com.yyysj.common.core.enums.UserIdentity;
import com.yyysj.common.security.exception.ServiceException;
import com.yyysj.common.security.service.TokenService;
import com.yyysj.system.domain.dto.LogonDTO;
import com.yyysj.system.domain.po.SysUser;
import com.yyysj.system.domain.dto.SysUserSaveDTO;
import com.yyysj.common.core.domain.LoginUserVO;
import com.yyysj.system.mapper.SysUserMapper;
import com.yyysj.system.service.ISysUserService;
import com.yyysj.system.utils.BCryptUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import java.util.List;

@RequiredArgsConstructor
@RefreshScope
@Service
public class SysUserServiceImpl implements ISysUserService {

    private final SysUserMapper sysUserMapper;

    private final TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;
    @Value("${admin.key}")
    private String registerKey;
    @Value("${admin.id}")
    private Long id;
    @Override
    public Result<String> login(String userAccont, String password) {
        // 0.创建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>()
                    .select(SysUser::getUserId, SysUser::getPassword, SysUser::getNickName)
                    .eq(SysUser::getUserAccount, userAccont);

        // 1.通过用户账号查询对应的密码
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

        // 2.判断账号是否存在
        if(sysUser == null) {
            return Result.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        // 3.判断密码是否正确
        // if(!password.equals(sysUser.getPassword())) {
        if(!BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            return Result.fail(ResultCode.FAILED_LOGIN);
        }

        // 4.生成token
        String token = tokenService.createToken(sysUser.getUserId(),
                secret,
                UserIdentity.ADMIN.getValue(),
                sysUser.getNickName(),
                "");

        return Result.ok(token);
    }

    @Override
    public Result<?> logout(String token) {
        // 将前端发送的token进行裁剪
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }

        if(!tokenService.deleteLoginUser(token, secret)) {
            return Result.fail();
        }

        return Result.ok();
    }

    @Override
    public int logon(LogonDTO logonDTO) {
        // 0.创建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUserId, SysUser::getPassword, SysUser::getNickName)
                .eq(SysUser::getUserAccount, logonDTO.getAccount());

        // 1.通过用户账号查询对应的密码
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

        // 2.判断账号是否存在
        if(sysUser != null) {
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }

        // 3.判断密码是否一致
        if(!logonDTO.getPassword().equals(logonDTO.getConfirmPassword())) {
            throw new ServiceException(ResultCode.FAILED_PASSWORD_NOT_SAME);
        }

        // 4.判断秘钥是否一致
        if(!logonDTO.getRegisterKey().equals(registerKey)) {
            throw new ServiceException(ResultCode.FAILED_REGISTER_KEY_NOT_SAME);
        }

        // 5.插入用户信息
        sysUser = new SysUser();
        sysUser.setUserAccount(logonDTO.getAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(logonDTO.getPassword()));
        sysUser.setNickName(logonDTO.getNickname());
        sysUser.setCreateBy(id);
        return sysUserMapper.insert(sysUser);
    }

    @Override
    public Result<?> save(SysUserSaveDTO sysUserSaveDTO) {
        // 0.通过用户账号查询用户是否存在
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount());

        List<SysUser> sysUsers = sysUserMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(sysUsers)) {
            return Result.fail(ResultCode.AILED_USER_EXISTS);
        }
        // 1.将SysUserSaveDTO转为SysUser
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserSaveDTO, sysUser);

        // 2.将密码进行加密
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUser.getPassword()));
        int insert = sysUserMapper.insert(sysUser);
        if(insert == 1) {
            return Result.ok();
        } else {
            return Result.fail(ResultCode.FAILED);
        }
    }

    @Override
    public Result<LoginUserVO> info(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if(loginUser == null) {
            return Result.fail();
        }

        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName());
        return Result.ok(loginUserVO);
    }
}
